// pages/annualHousingFund/annualHousingFund.js
Page({
  data: {
    annualGjjCheckbox:[1],
    totalAnnualGjj:'0.00',
    annualGjjEnd:['结束时间'],
    annualGjjStart:['开始时间'],
    annualGjjStandard:[''],
    gjjRate:['0%','5%','6%','7%','8%','9%','10%','11%','12%','20%'],
    nowYear:"",
    annualGjjRatioIndex:[0]
    // index2:0
  },
  
  insert(e){
    var cb = this.data.annualGjjCheckbox;
    var start = this.data.annualGjjStart;
    var end = this.data.annualGjjEnd;
    var gjjStandard = this.data.annualGjjStandard;
    var index1 = this.data.annualGjjRatioIndex;
    start.push('开始时间');
    cb.push(cb.length+1);
    end.push('结束时间');
    gjjStandard.push('');
    index1.push(0);
    this.setData({annualGjjStart:start,annualGjjEnd:end,annualGjjCheckbox:cb,annualGjjStandard:gjjStandard,annualGjjRatioIndex:index1});
  },

  delBind(e){
    var cb = this.data.annualGjjCheckbox;
    var start = this.data.annualGjjStart;
    var end = this.data.annualGjjEnd;
    var gjjStandard = this.data.annualGjjStandard;
    var index1 = this.data.annualGjjRatioIndex;
    start.pop();
    cb.pop();
    end.pop();
    gjjStandard.pop();
    index1.pop();
    this.setData({annualGjjStart:start,annualGjjEnd:end,annualGjjCheckbox:cb,annualGjjStandard:gjjStandard,annualGjjRatioIndex:index1});
  },

  //可用方法2
  calMonths(start,end){
    if(start === null || end === null){
      return -1;
    }
    var head = Number(start.slice(-2));
    // console.log(head)
    var tail = Number(end.slice(-2));
    return tail - head + 1;
  },
 /**
 * 
 * @param {String} dateStr1 
 * @param {String} dateStr2 
 */
compareDate:function(dateStr1,dateStr2){
  const date1 = new Date(dateStr1);
  const date2 = new Date(dateStr2);
  if (date1 > date2) {
      return 1;
  } else if (date1 < date2) {
      return 2;
  } else {
      return 0;
  }
},

calMonthInThisYear:function(startStr,endStr){
  var end = endStr;
  var start = startStr;
  var calStart = this.data.nowYear;
  calStart = calStart.concat("-01")
  var calEnd =  this.data.nowYear;
  calEnd = calEnd.concat("-12");
  var result = 0;
  //传入其他字符串，直接返回0
  if(end.indexOf("-") === -1 || start.indexOf("-") === -1){
    return 0;
  }
  var startComCal = this.compareDate(calStart,start);
  var calComEnd = this.compareDate(calEnd,end);
  var endComYearStart = this.compareDate(calStart,end);
  var startComYearEnd = this.compareDate(calEnd,start);
  // start <= 本年1月
  if(startComYearEnd == 2){
    return -1;
  }   
  if(startComCal <= 1){
    //本年12月 < end,完整包含整个本年度，直接返回12月
    if(calComEnd === 2)result = 12;
    //本年1月<end<本年12月
    else if(endComYearStart === 2 && calComEnd <= 1){
      result = Number(end.slice(-2))
    }
  }
  // 当start大于本年1月
  else if(startComCal === 2)
  {
    // end小于calEnd
    if(calComEnd <= 1){
      result = Number(end.slice(-2)) - Number(start.slice(-2)) + 1;
    }
    // end大于本年12月
    else{
      result = 12 - Number(start.slice(-2)) + 1;
    }
  }
  return result;
},


  //unfinished
  calGongjijinCount(){
    var sbStandard = this.data.annualGjjStandard;
    var index1 = this.data.annualGjjRatioIndex;
    var sbRate = this.data.gjjRate;
    var start = this.data.annualGjjStart;
    var end = this.data.annualGjjEnd;
    var cb = this.data.annualGjjCheckbox
    var result = 0,rateTemp = 0,num = 0,months = 0;
    var head = '',tail = '',tagT = '1900-01',tagH = '1900-01'; 
    for(var i = 0;i < cb.length;i++){
      months = this.calMonthInThisYear(start[i],end[i])
      if(months === 0){
        // 不好好填的都不算数，直接是0。
        continue;
      }else if(months === -1){
        return -1;
      }
      else{
        num = index1[i];
        tail = end[i],head = start[i];
        rateTemp = Number(sbRate[num].slice(0,-1));
        if((this.compareDate(tail,tagH) === 2 || this.compareDate(tagT,head) === 2) && sbStandard[i] != ''){
          result = result + rateTemp * Number(sbStandard[i]) / 100 * months;
        }else{
          //有时间区间重复，直接返回-1，提示用户重新填写。
          return -1.0
        }
      }
      tagH = start[i],tagT = end[i];
    }    
    result = result.toFixed(2);
    this.setData({totalAnnualGjj:result.toString()});
  },

  bindStartDateChange(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var start = this.data.annualGjjStart;
    start[nowIdx] = value;
    this.setData({annualGjjStart:start});
  },

  bindEndDateChange(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var end = this.data.annualGjjEnd;
    var start = this.data.annualGjjStart;
    if(start[nowIdx].indexOf("-") === -1){
      wx.showToast({
        title: '请先输入开始时间！',
        icon:'none'
      });
      return;
    }
    end[nowIdx] = value;
    this.setData({annualGjjEnd:end});
  },
  
  bindPickerGjjRate(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var index1 = this.data.annualGjjRatioIndex;
    index1[nowIdx] = e.detail.value
    this.setData({annualGjjRatioIndex:index1});
  },
  
  onGjjCount(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var gjjStandard = this.data.annualGjjStandard;
    if(/^(0|[1-9][0-9]*)$/.test(value) || /^([1-9][0-9]*\.)$/.test(value) || /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/.test(value)){
      gjjStandard[nowIdx] = value;
      this.setData({annualGjjStandard:gjjStandard});
      return;
    }else{
       wx.showToast({
         title: '请正确输入公积金缴纳基数！\r\n(仅数字，最多2位小数)',
         icon:'none'
       });
       gjjStandard[nowIdx] = '';
       this.setData({annualGjjStandard:gjjStandard});
       return;
    }
  },
 
  onCompute(){
    var val = this.calGongjijinCount();
    // app.globalData.gjjStart = this.data.gjjStart;
    // app.globalData.gjjStandard = this.data.gjjStandard;
    // app.globalData.gjjEnd = this.data.gjjEnd;
    // app.globalData.gjjIndex = this.data.gjjIndex;
    if(val < 0){
      wx.showToast({
        title: '请正确填写！\r\n1.时间区间不能有重合\r\n2.有未完整的内容或错误填写',
        icon:'none',
        duration: 3000
      });
      return;
    }
    const gjjBox   = JSON.stringify(this.data.annualGjjCheckbox)
    const gjjStart  = JSON.stringify(this.data.annualGjjStart)
    const gjjEnd  = JSON.stringify(this.data.annualGjjEnd)
    const gjjStandard   = JSON.stringify(this.data.annualGjjStandard)
    const gjjIndex   = JSON.stringify(this.data.annualGjjRatioIndex)
    wx.setStorageSync('annualGjjCheckbox',gjjBox);
    wx.setStorageSync('annualGjjStart',gjjStart);
    wx.setStorageSync('annualGjjEnd',gjjEnd);
    wx.setStorageSync('annualGjjStandard',gjjStandard);
    wx.setStorageSync('annualGjjRatioIndex',gjjIndex);
  
    var total = this.data.totalAnnualGjj;
    wx.showToast({
      title: '计算成功！',
      icon: 'sucess',
      duration: 2000,
      success: (res)=> {
        setTimeout(function() {
          let pages = getCurrentPages();//当前页面
          let prevPage = pages[pages.length - 2 ];
          prevPage.setData({
            // securate:value,
            // secondSecurity:that.data.sbStandard,
            annualGongjijing:total
          });
          wx.navigateBack({
            delta: 1 
          })
        }, 2000);
      }
  });
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showShareMenu({
      withShareTicket:true,
      menus:["shareAppMessage",'shareTimeline']});
    const mon = options.calYear;
    this.setData({nowYear:mon});
    console.log(mon);
  },

  formReset:function(){
    this.setData({
      annualGjjCheckbox:[1],
      totalAnnualGjj:'0.00',
      annualGjjEnd:['结束时间'],
      annualGjjStart:['开始时间'],
      annualGjjStandard:[''],
      gjjRate:['0%','5%','6%','7%','8%','9%','10%','11%','12%','20%'],
      annualGjjRatioIndex:[0]
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   * 
   */
  onShow() {
    let that = this;
    var value = wx.getStorageSync('annualGjjCheckbox');
    if(value){
      that.setData({annualGjjCheckbox:JSON.parse(value)})
    }
    value = wx.getStorageSync('annualGjjStart');
    if(value){
      that.setData({annualGjjStart:JSON.parse(value)})
    }
    value = wx.getStorageSync('annualGjjEnd');
    if(value){
      that.setData({annualGjjEnd:JSON.parse(value)})
    }
    value = wx.getStorageSync('annualGjjStandard');
    if(value){
      that.setData({annualGjjStandard:JSON.parse(value)})
    }
    value = wx.getStorageSync('annualGjjRatioIndex');
    if(value){
      that.setData({annualGjjRatioIndex:JSON.parse(value)})
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})